/*
 * AbstractFacadeImpl.java
 *
 * Created on 1 2007  2:15
 *
 * To change this template, choose Tools | Template Manager
 * and open the template in the editor.
 */

package com.persistent.model;

import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.annotation.Resource;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.EntityTransaction;
import javax.persistence.Persistence;
import javax.persistence.PersistenceUnit;
import javax.transaction.HeuristicMixedException;
import javax.transaction.HeuristicRollbackException;
import javax.transaction.NotSupportedException;
import javax.transaction.RollbackException;
import javax.transaction.SystemException;
import javax.transaction.UserTransaction;
import javax.annotation.Resource.AuthenticationType;

/**
 *
 * @author alexog
 */
public abstract class AbstractFacadeImpl<V> implements AbstractFacade<V>{
    protected EntityManagerFactory emf;
    
    protected EntityTransaction etx;
    
    protected EntityManager em;
    
    public AbstractFacadeImpl() {
        emf = Persistence.createEntityManagerFactory("TankProjectPU");
        this.em = this.getEntityManager();
        this.initEntityTransaction();
    }
    
    abstract public void create(V v);
    
    public void edit(V v) {
        em.merge(v);
    }
    
    public void destroy(V v) {
        em.merge(v);
        em.remove(v);
    }
    
    abstract public V find(V v);
    
    abstract public List<V> findAll();
    
    public void update() {
        etx.begin();
        em.flush();
        etx.commit();
    }
    
    public EntityManager getEntityManager() {
        return emf.createEntityManager();
    }
    
    public EntityTransaction getEntityTransaction() {
        return em.getTransaction();
    }
    
    public void initEntityTransaction() {
        etx = getEntityTransaction();
    }
    
    public void close() {
        em.close();
        emf.close();
    }
    
    public void open() {
        if (!emf.isOpen()) {
            if (!em.isOpen()) {
                emf = Persistence.createEntityManagerFactory("TankProjectPU");
                this.em = this.getEntityManager();
                this.initEntityTransaction();   
            }
        }
    }
}
